<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetData, GetExcelData, PostMembershipSendscore } from '@/api/modules/membership'
import storage from '@/utils/storage'
import GetCacheData from '@/store/modules/NewPageCache'

// const imgDomain = 'https://img1.eprhan.cc'
const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('membership').currentPage

const findFrom = ref({
  ...(cacheData.GetCacheData('membership').fromData),
})
const dataList: any = ref([])
const loading = ref(true)
const total = ref(0)
let excelTotal = 0

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.Mobile && ({ Mobile: findFrom.value.Mobile })),
    ...(findFrom.value.VipLevel && ({ VipLevel: findFrom.value.VipLevel })),
    ...(findFrom.value.Time.length !== 0 && ({ StartAddTime: findFrom.value.Time[0], EndAddTime: findFrom.value.Time[1] })),
  }
  GetData(params).then((res: any) => {
    if (res.statusCode === 200) {
      dataList.value = res.data.items
      total.value = res.data.total
      if (total.value > excelTotal) {
        excelTotal = total.value
      }
      loading.value = false
    }
    else {
      ElMessage.error('获取数据失败')
      loading.value = false
    }
  })
}

async function ExportExcel() {
  const params = {
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.Mobile && ({ Mobile: findFrom.value.Mobile })),
    ...(findFrom.value.VipLevel && ({ VipLevel: findFrom.value.VipLevel })),
    ...(findFrom.value.Time.length !== 0 && ({ StartAddTime: findFrom.value.Time[0], EndAddTime: findFrom.value.Time[1] })),
  }
  try {
    const response: any = await GetExcelData(params)
    // console.log(response)

    const a = document.createElement('a')
    const binaryData = []
    binaryData.push(response)
    a.href = window.URL.createObjectURL(
      new Blob(binaryData, {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=UTF-8',
      }),
    )
    a.download = (storage.local.get('fileName') as string)
    storage.local.remove('fileName')
    a.click()
    URL.revokeObjectURL(a.href)
  }
  catch (error) {
    // 请求失败处理
    console.error(error)
  }
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('membership').currentSize)
  cacheData.SetCacheData('membership', PageNum, cacheData.GetCacheData('membership').currentSize, findFrom.value)
}

const integralDialog = ref(false)

const inregralTypeOption = [
  { value: 71, label: '社群互动答题奖励' },
]

const integralFrom = ref({
  openId: '',
  userPhone: '',
  score_type: 71,
  score: 50,
  score_desc: '社群互动答题奖励',
})

function SetIntegral(item: any) {
  integralFrom.value.userPhone = item.subscriber?.userPhone
  integralFrom.value.openId = item.subscriber?.scOpenId
  integralDialog.value = true
}

function SetIntegralData() {
  ElMessageBox.confirm(
    `您确定要为手机号为${integralFrom.value.userPhone}的用户发放积分吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      const params = {
        openId: integralFrom.value.openId,
        scoreType: integralFrom.value.score_type,
        score: integralFrom.value.score,
        scoreDesc: integralFrom.value.score_desc,
      }
      // console.log(params)
      PostMembershipSendscore(params).then((res: any) => {
        if (res.statusCode === 200) {
          integralDialog.value = false
          GetDataList(cacheData.GetCacheData('membership').currentPage, cacheData.GetCacheData('membership').currentSize)
        }
        else {
          if (typeof res.errors === 'string') {
            ElMessage.error(`发放失败。${res.errors}`)
          }
          else {
            let errorStr = ''
            for (const key in res.errors) {
              errorStr += `${key}：${res.errors[key]}；`
            }
            ElMessage.error(`发放失败。${errorStr}`)
          }
        }
      })
      ElMessage({
        type: 'success',
        message: '发放成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消发放',
      })
    })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('membership', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('membership').currentSize)
  cacheData.SetCacheData('membership', val, cacheData.GetCacheData('membership').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('membership').currentPage || 1
})

onMounted(() => {
  GetDataList(cacheData.GetCacheData('membership').currentPage, cacheData.GetCacheData('membership').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="findFrom.Mobile" placeholder="请输入手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="会员等级">
                <el-input v-model="findFrom.VipLevel" placeholder="请输入会员等级" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="时间">
                <el-date-picker
                  v-model="findFrom.Time"
                  clearable
                  type="datetimerange"
                  range-separator="到"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @keyup.enter="Inquire"
                />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="ExportExcel">
          导出数据
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
        <el-table-column align="center" width="100" prop="id" label="ID" />
        <el-table-column align="center" prop="subscriber.userId" label="用户ID" width="120" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="330">
          <template #default="scope">
            <div v-if="!scope.row.subscriber">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.subscriber?.userNickName }}
                </p>
                <span>
                  {{ scope.row.subscriber?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300" prop="subscriber.scOpenId" label="用户OpenID" />
        <el-table-column align="center" width="200" prop="birthDay" label="出生月日" />
        <el-table-column align="center" width="100" prop="vipLevel.vipLevel" label="会员等级" />
        <el-table-column align="center" width="140" prop="vipLevel.vipName" label="会员等级名称" />
        <el-table-column align="center" width="140" prop="currentScore" label="当前积分" />
        <el-table-column align="center" width="140" prop="totalScore" label="累计积分" />
        <el-table-column align="center" width="140" prop="orderScore" label="下单积分" />
        <el-table-column align="center" width="140" prop="initialChannel" label="初始开通渠道">
          <template #default="scope">
            <el-tag>
              {{ scope.row.initialChannel === 1 ? '微信小程序' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" width="140" prop="vipState" label="状态">
          <template #default="scope">
            <el-tag>
              {{ scope.row.vipState === 1 ? '正常' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" width="240" prop="addTime" label="添加时间" />
        <el-table-column align="center" width="240" prop="updateTime" label="更新时间" />
        <el-table-column align="center" label="操作" fixed="right" min-width="140">
          <template #default="scope">
            <div class="table-button">
              <el-button type="success" @click="SetIntegral(scope.row)">
                赠送积分
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('membership').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <el-dialog v-model="integralDialog" title="赠送积分" width="500">
      <el-form :model="integralFrom">
        <el-form-item label="用户手机号：" label-width="100px">
          <span>{{ integralFrom.userPhone }}</span>
        </el-form-item>
        <el-form-item label="类型" label-width="80px">
          <el-select v-model="integralFrom.score_type" placeholder="Please select a zone">
            <el-option v-for="item in inregralTypeOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分数量" label-width="80px">
          <el-input v-model="integralFrom.score" disabled />
        </el-form-item>
        <!-- <el-form-item label="描述" label-width="80px">
          <el-input v-model="integralFrom.score_desc" type="textarea" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="integralDialog = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetIntegralData">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;
  margin-right: 25px;

  div {
    text-align: left;
  }
}
</style>
